package com.t3.display
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.utils.IExternalizable;
	import flash.utils.IDataInput;
	import flash.utils.IDataOutput;
	import flash.net.registerClassAlias;

	public class StageObject extends Sprite implements IStageObject, IExternalizable
	{
		public function StageObject()
		{
			registerClassAlias( "com.t3.display.StageObject", StageObject );
			super();
		}
		
		public function get stageX():uint
		{
			return this.localToGlobal( new Point( 0, 0 ) ).x;
		}
		
		public function get stageY():uint
		{
			return this.localToGlobal( new Point( 0, 0 ) ).y;
		}
		
		public function get stageLoc():Point
		{
			return this.localToGlobal( new Point( 0, 0 ) );
		}
		
		public function set stageLoc( point:Point ):void
		{
			var parLoc:Point = new Point( 0, 0 );
			
			if( parent != null )
			{			
				if( parent is StageObject )
				{
					parLoc = (StageObject) (parent).stageLoc;	
				}
				else
				{
					parLoc = parent.localToGlobal( new Point( 0, 0 ) );
				}
			}
			
			this.location = new Point( point.x - parLoc.x, point.y - parLoc.y );
		}
		
		public function set location( point:Point ):void
		{
			this.x = point.x;
			this.y = point.y; 
		}
		
		public function get location():Point
		{
			return new Point( this.x, this.y );
		}
		
		public function relLoc( so:StageObject ):Point
		{
			if( so != null )
			{
				return new Point( this.stageX - so.stageX, this.stageY - so.stageY );
			}
			else
			{
				return location;
			}
		}
		
		public override function addChild( child:DisplayObject ):DisplayObject
		{
			if( child is StageObject )
			{
				var so:StageObject = (StageObject) (child);
				
				so.location = so.relLoc( this );
			}
			
			super.addChild( child );
			
			return child;
		}
		
		public function writeExternal(output:IDataOutput):void 
		{
			output.writeObject(this.stageLoc);
		}

		public function readExternal(input:IDataInput):void
		{
			this.stageLoc = input.readObject();
		}
	}
}